package com.coolshark.shop.controller;

import com.coolshark.shop.entity.User;
import com.coolshark.shop.mapper.LoginMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {

    @Autowired
    LoginMapper mapper;

    @RequestMapping("/login")
    public int login(@RequestBody User user, HttpSession session, HttpServletResponse response) {
        System.out.println("user = " + user);
        User u = mapper.selectByUsername(user.getUsername());
        if (u != null) {
            if (user.getPassword().equals(u.getPassword())) {
                session.setAttribute("user", u);
                //如果用户勾选了记住,则创建Cookie把用户名和密码保存到Cookie中下发给客户端
                if (user.getRem()) {
                    Cookie c1 = new Cookie("username", u.getUsername());
                    Cookie c2 = new Cookie("password", u.getPassword());
                    //下发给客户端
                    response.addCookie(c1);
                    response.addCookie(c2);
                    //设置Cookie保存时间,数据会保存到磁盘
                    c1.setMaxAge(60 * 60 * 60 * 24 * 30);
                }
                return 1;
            }
            return 3;
        }
        return 2;
    }

    @RequestMapping("/currentUser")
    public User currentUser(HttpSession session) {
        //从会话对象中获取登录成功时保存的对象
        return (User) session.getAttribute("user");
    }

    @RequestMapping("/loginout")
    public void loginout(HttpSession session) {
        //删除登录成功是保存的user对象|
        session.removeAttribute("user");
    }
}
